#name : template binary exact ci by simulation
# key : bin.exact.ci.simulation.template
# contributor: Shuguang Sun
# --
${1:binary_exact} <- function(N = 20, true_p = 0.5,
                         target_p = 0.35, LCL_boundary = target_p, alpha = 0.05,
                         R = 1000, seed = NULL) {
  if (!is.null(seed) & is.numeric(seed)) {
    set.seed(seed)
  }

  r1 <- rbinom(R, N, true_p)
  f1 <- (r1 / N >= target_p)

  exactlo <- qbeta(alpha / 2, r1, N - r1 + 1)
  #  exacthi <- qbeta(1 - alpha/2, r1 + 1, N - r1)
  f2 <- (exactlo > LCL_boundary)

  list(alpha = alpha,
       true_p = true_p,
       target_p = target_p,
       N = N,
       prob_ge_target = sum(f1)/R,
       prob_lcl_gt_boundary = sum(f2)/R)
}

alpha <- c(0.05, 0.1)
target_ORR <- c(0.3, 0.35, 0.4)
target_p <- c(0.2, 0.25)
N <- seq.int(35, 90, by = 1)

params <- expand.grid(N = N, true_p = target_ORR, target_p = target_p, alpha = alpha)
paramsl <- lapply(seq_len(nrow(params)), function(i) params[i, ])

pows <- sapply(paramsl, $1)
powsd <- as.data.frame(pows)
colnames(powsd) <- c("alpha", "true_p", "target_p", "N", "prob_ge_target", "prob_lcl_gt_boundary")

powsd <- powsd |>
  dplyr::mutate(var = as.factor(sprintf("%3.2f_%3.2f", true_p, target_p)))

library("dplyr")
library("ggplot2")
p3 <- ggplot({powsd |> filter(alpha == 0.05)},
             aes(x = N, y = prob_lcl_gt_boundary, colour = factor(true_p), linetype = factor(th1))) +
  geom_line(size = 1) +
  geom_hline(yintercept = 0.8, linetype="dotdash", color = "red", size = 0.9) +
  ## scale_y_continuous(breaks=c(0, 0.25, 0.50, 0.75, 0.8, 1), labels = c(0, 0.25, 0.50, 0.75, 0.8, 1)) +
  scale_y_continuous(labels = scales::percent) +
  scale_linetype_manual(values=c("solid", "dashed"))+
  scale_colour_brewer(palette = "Set2") +
  xlab("Number of Patients") +
  ylab(expression(paste("Probability of 95% LCL > ", theta))) +
  labs(colour = "True P", linetype = expression(paste("Limit ", theta))) +
  theme(
    axis.text.x = element_text(),
    axis.title.x = element_text(size=14),
    axis.title.y = element_text(size=14),
    legend.justification = c(1, 0),
    legend.position = c(1, 0),
    legend.text = element_text(size = 12),
    legend.background = element_rect(fill = "transparent")
  )
p3

dev.off()
